#! /bin/sh

erl -pa ../src -sname s3nodefinder_test1 -eval '
  { ok, [ { _, _, PropList } ] } = file:consult ("../src/s3nodefinder.app"),
  { value, { _, Env } } = lists:keysearch (env, 1, PropList),
  { value, { _, AccessFile } } = lists:keysearch (access_key_id_file, 1, Env),
  { value, { _, SecretFile } } = lists:keysearch (secret_access_key_file, 1, Env),
  { ok, AccessKeyIdBinary } = file:read_file (AccessFile),
  s3nodefindersup:start_link (binary_to_list (AccessKeyIdBinary),
                              SecretFile,
                              "/dukes_test/"),
  receive after 10000 -> ok end
' -noshell -noinput -s init stop &

erl -pa ../src -sname s3nodefinder_test2 -eval '
  "s3nodefinder_test2@" ++ Host = atom_to_list (node ()),
  [] = erlang:nodes (),
  { ok, [ { _, _, PropList } ] } = file:consult ("../src/s3nodefinder.app"),
  { value, { _, Env } } = lists:keysearch (env, 1, PropList),
  { value, { _, AccessFile } } = lists:keysearch (access_key_id_file, 1, Env),
  { value, { _, SecretFile } } = lists:keysearch (secret_access_key_file, 1, Env),
  { ok, AccessKeyIdBinary } = file:read_file (AccessFile),
  s3nodefindersup:start_link (binary_to_list (AccessKeyIdBinary),
                              SecretFile,
                              "/dukes_test/"),
  receive after 3000 -> ok end,
  Other = list_to_atom ("s3nodefinder_test1@" ++ Host),
  [ Other ] = erlang:nodes ()
' -noshell -noinput -s init stop || exit 1

# check that s3 bucket is nonempty
s3-get -k `cat /usr/share/dukes/access-key-id`                          \
       -s /usr/share/dukes/secret-access-key                            \
       -S '/dukes_test/?prefix=no' 2>/dev/null |                        \
 grep '<Key>node.s3nodefinder_test' >/dev/null || exit 1

wait

# check that s3 bucket is empty
! s3-get -k `cat /usr/share/dukes/access-key-id`  \
         -s /usr/share/dukes/secret-access-key    \
         -S '/dukes_test/?prefix=no' 2>/dev/null | \
   grep '<Key>node.s3nodefinder_test' 
